<script setup lang="ts" name="AccountManager">
import pageContainer from '@/components/pageContainer.vue'
import {ref, reactive, onActivated} from 'vue'
import {HeaderData} from '@/components/dTable/dTable'
import {FormRules, ElMessage, ElMessageBox} from 'element-plus'
import {
  OperButton,
  SearchFromItem,
  SearchButton,
  SearchFromJustify
} from '@/components/dTable/dHeader'
import {
  PageConfig,
  defaultPage,
  defaultPageSize,
  defaultPageSizes,
  defaultLayout
} from '@/components/dTable/dFooter'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import operation from '@/components/dTable/components/operation.vue'
import colorType from '@/components/dTable/components/colorType.vue'
import {
  UserSave,
  UserEdit,
  userRemove,
  getAccountList,
  userResetPwd,
  changeStatus,
  AccountParams,
  AccountList,
  roleNameList
} from '@/api/baseSetting/accountManager'
import addAccount from './addAccount.vue'
import {
  Alphanumeric,
  transfDicArrData,
  PhoneNumber,
  NoNumber,
  NotLeadingAndTrailingSpaces
} from '@/util/common'
import {SeleteData} from '@/api/config'
import userCommon from '@/store/common'
const common = userCommon.setup().store

//搜索
const searchFromData = reactive<AccountParams>({
  loginName: '',
  username: '',
  phone: '',
  roleId: ''
})
const searchFromRules = reactive<FormRules>({
  loginName: [
    {
      message: '长度应不超过20个字符',
      max: 20,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入字母、数字',
      pattern: Alphanumeric,
      trigger: ['change', 'blur']
    }
  ],
  userName: [
    {
      message: '长度应不超过20个字符',
      trigger: ['change', 'blur'],
      max: 20
    },
    {
      message: '请输入汉字、字母、字符',
      pattern: NoNumber,
      trigger: ['change', 'blur']
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  phone: [
    {
      message: '长度应是11位',
      max: 11,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入正确的联系电话',
      pattern: PhoneNumber,
      trigger: ['change', 'blur']
    }
  ]
})
// 基础数据
const emtyBtnData = {
  username: '',
  phone: '',
  password:'',
  id: '',
  role: ''
}
const addBtnData = ref<UserSave | UserEdit>(emtyBtnData)
// 岗位下拉
const postSeleteData = ref<Array<SeleteData>>([])
// 角色下拉
const roleSeleteData = ref<Array<SeleteData>>([])
//获取角色下拉
const roleName = () => {
  roleSeleteData.value.length = 0
  roleNameList()
    .then((res) => {
      const {data} = res.data
      data?.map((item) => {
        roleSeleteData.value.push({
          label: item.roleName,
          value: item.id
        })
      })
    })
    .catch((error) => {
      console.warn(error)
    })
}

//数据
const tableData = ref<Array<AccountList>>([])
//表单清除控制
const resetFieldsFlag = ref(false)
//默认选中
const defualtSeleted = ref<AccountList | undefined>(undefined)

// 页面选中的数据
const pageData = ref<Array<AccountList>>()

// 多选的数据
const pagesData = ref<Array<AccountList>>([])

//显示加载状态
const showLoading = ref(false)

//下拉选择数据
const addBtnTitle = ref('')

//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'username',
    label: '姓名',
    columnType: 'text',
    align: 'left',
    'min-width': '139'
  },
  {
    prop: 'phone',
    label: '联系电话',
    columnType: 'text',
    align: 'left',
    'min-width': '181'
  },
  {
    prop: 'password',
    label: '密码',
    columnType: 'text',
    align: 'left',
    'min-width': '181'
  },
  {
    prop: 'button',
    label: '操作',
    columnType: 'slot',
    align: 'left',
    width: '200',
    fixed: 'right'
  }
])

//表头
const operButtons = ref<Array<OperButton>>([
  {
    label: '新增',
    type: 'noraml',
    iconConfig: {icon: 'common-add', type: 'custom'},
    code: 'add'
  }
])

//搜索项
const searchFromItems = ref<Array<SearchFromItem>>([
  {
    label: '姓名',
    placeholder: '请输入姓名',
    type: 'input',
    enterSubmit: true,
    prop: 'username'
  },
  {
    label: '联系电话',
    placeholder: '请输入联系电话',
    type: 'input',
    enterSubmit: true,
    prop: 'phone'
  }
])

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([
  {type: 'search'},
  {type: 'clear'}
])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})
//搜索数据
const searchData = (index?: number) => {
  showLoading.value = true
  const params: AccountParams = {
    username: searchFromData.username ? searchFromData.username : undefined,
    phone: searchFromData.phone ? searchFromData.phone : undefined,
    roleId: searchFromData.roleId ? searchFromData.roleId : undefined,
    status: searchFromData.status,
    page: pageConfig.value.currentPage,
    limit: pageConfig.value.pageSize
  }
  getAccountList(params)
    .then((res) => {
      pageConfig.value.total = res.data.data.total === null ? 0 : res.data.data.total
      const iconConfig2: OperButton = {
        label: '编辑',
        type: 'noraml',
        iconConfig: {
          icon: 'common-edit',
          type: 'custom',
          color: '#1C9399',
          size: 20
        },
        code: 'edit'
      }
      const iconConfig4: OperButton = {
        label: '删除',
        type: 'noraml',
        iconConfig: {
          icon: 'common-delete',
          type: 'custom',
          color: 'rgb(225,56,72)',
          size: 20
        },
        code: 'remove'
      }
      console.log('res.data.data', res.data.data)

      res.data.data.list.forEach((resData) => {
        if (resData.status === 0) {
          resData.button = [iconConfig2, iconConfig4]
        } else {
          resData.button = [iconConfig2, iconConfig4]
        }
        // resData.status === 0 ? '停用' : '启用'
        // resData.colorType = resData.status === 0 ? '停用' : '启用'
      })
      tableData.value = res.data.data.list as any
      if (index !== undefined && tableData.value[index]) {
        defualtSeleted.value = tableData.value[index]
      } else {
        defualtSeleted.value = undefined
      }
    })
    .catch((err) => {
      console.warn(err)
    })
    .finally(() => {
      showLoading.value = false
    })
}

//行选中事件
const onRowClick = (row) => {
  pageData.value = row
}

//多选事件
const onMultipleSelection = (rows: Array<AccountList>) => {
  pagesData.value = rows
}

//搜索事件
const onSubmit = () => {
  searchData(0)
}
//清空搜索表单事件
const onFormClear = () => {
  searchData(0)
}
const showAddBtn = ref(false)
// 新增
const onAddAccount = () => {
  addBtnData.value = {...emtyBtnData}
  addBtnTitle.value = '新增账号'
  showAddBtn.value = true
}
// 重置密码
const onClickTip = (row: AccountList) => {
  ElMessageBox.confirm('是否确认重置此账号密码？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      return userResetPwd({userId: row.id})
    })
    .then((res) => {
      ElMessage({
        type: 'success',
        message: res.data.msg ? res.data.msg : '重置密码成功'
      })
    })
}

//操作按钮事件
const onOperation = (code: string) => {
  if (code === 'add') {
    onAddAccount()
  }
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(0)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData(0)
}

const deleteAccount = (row: AccountList) => {
  ElMessageBox.confirm('确认删除当前账号？', '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      return userRemove(row.id)
    })
    .then(() => {
      ElMessage.success('删除成功')
      searchData(0)
    })
}

const stopAccount = (row: AccountList) => {
  if (row.status === 0) {
    ElMessageBox.confirm('是否启用当前账号？', '启用确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        return changeStatus({userId: row.id, status: row.status === 0 ? 1 : 0})
      })
      .then((res) => {
        if (res.data.code === 200) ElMessage.success('启用成功')
        searchData(0)
      })
  } else {
    ElMessageBox.confirm('是否停用当前账号？', '停用确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        return changeStatus({userId: row.id, status: row.status === 0 ? 1 : 0})
      })
      .then((res) => {
        if (res.data.code === 200) ElMessage.success('停用成功')
        searchData(0)
      })
  }
}

//操作插槽事件
const cellOperation = (code: string, row) => {
  if (code === 'edit') {
    addBtnData.value = {
      id: row.id,
      username: row.username,
      phone: row.phone,
      password: row.password,
      role: row.role
    }
    addBtnTitle.value = '编辑账号'
    showAddBtn.value = true
  }
  if (code === 'remove') {
    deleteAccount(row)
  }
  if (code === 'stop') {
    stopAccount(row)
  }
  if (code === 'reset') {
    onClickTip(row)
  }
}

const onCloseAddBtn = () => {
  showAddBtn.value = false
  resetFieldsFlag.value = !resetFieldsFlag.value
}
const refresh = () => {
  searchData(0)
}

onActivated(() => {
  searchData(0)
})
</script>
<template>
  <page-container>
    <d-table-promote
      :oper-buttons="operButtons"
      :search-form-items="searchFromItems"
      :search-buttons="searchButtons"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-from-justify="searchFromJustify"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :show-loading="showLoading"
      :stripe="true"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @row-click="onRowClick"
      @multiple-selection="onMultipleSelection"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #button="scope">
        <operation
          :row="scope.row"
          :col="scope.item"
          @opertion-click="cellOperation"
        />
      </template>
      <template #colorType="scope">
        <colorType :row="scope.row" :col="scope.item" />
      </template>
    </d-table-promote>
  </page-container>
  <add-account
    v-if="showAddBtn"
    :post-selete-data="postSeleteData"
    :role-selete-data="roleSeleteData"
    :show-dialog="showAddBtn"
    :title="addBtnTitle"
    :btn-data="addBtnData"
    @close="onCloseAddBtn"
    @refresh="refresh"
  />
</template>

<style scoped>
.test-con {
  margin: 50px;
}
.test-tablecon {
  height: 500px;
}
.test-box {
  height: 20px;
  background-color: rgba(128, 0, 128, 0.5);
  border-radius: 5px;
}
</style>
<style>
.mater-manger-test .el-form-item__label {
  width: 78px !important;
}
</style>
